package com.crr.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class RateLimitController {
    /**
     * rest地址限流+默认限流返回
     *
     * @return
     */
    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按照Rest地址限流测试OK";
    }

    /**
     * 资源名称限流+自定义限流返回
     *
     * @return
     */
    @GetMapping("/rateLimit/byResource")
    @SentinelResource(value = "byResourceSentinelResource", blockHandler = "handlerBlockHandler")
    public String byResource() {
        return "按照资源名称SentinelResource限流测试OK好好";
    }

    public String handlerBlockHandler(BlockException blockException) {
        return "服务不可用触发了@SentinelResource启动--------";
    }

    /**
     * 资源名称限流+自定义限流返回+服务降级处理
     *
     * @return
     */
    @GetMapping("/rateLimit/doAction/{p1}")
    @SentinelResource(value = "doActionSentinelResource", blockHandler = "doActionBlockHandler", fallback = "doActionFallback")
    public String byResource2(@PathVariable("p1") Integer p1) {
        if (p1 == 0) {
            throw new RuntimeException("p1等于0 直接异常");
        }
        return "doAction";
    }

    public String doActionBlockHandler(@PathVariable("p1") Integer p1, BlockException blockException) {
        log.error("sentinel配置自定义限流了：{}", blockException);
        return "sentinel自定义限流了";
    }

    public String doActionFallback(@PathVariable("p1") Integer p1, Throwable t) {
        log.error("程序逻辑异常了：{}", t);
        return "程序逻辑异常了" + "\t" + t.getMessage();
    }

    /**
     * 热点规则
     * @param p1
     * @param p2
     * @return
     */
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotkey",blockHandler = "dealHandler_testHorKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "---------------testHotKey";
    }

    public String dealHandler_testHorKey(String p1,String p2,BlockException e){
        return "----------dealHandler_testHorKey";
    }
}
